package com.team7.happycommunity.gatway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.team7.happycommunity.gatway.utils.JWTUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;

/**
 * 物业登录拦截器
 */
@Component
public class PropertyLoginFilter extends ZuulFilter {

    @Autowired
    JWTUtils jwtUtils;

    @Value("${my.auth_verify.duration}")
    Long duration;

    @Value("${my.propertymanagement.name}")
    String applicationName;


    /**
     * 登录之后追加
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取当前
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = requestContext.getRequest();

        String uri = httpServletRequest.getRequestURI();
        if(uri.contains("/propertymanagement/user/login")){
            return true;
        }


        return false;
    }

    /**
     * 获取
     */
    @Override
    public Object run() {
        try {
            RequestContext requestContext = RequestContext.getCurrentContext();
            InputStream inputStream = requestContext.getResponseDataStream(); // 获取 ResponseData的流
            String result = StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));  // StreamUtils 对流进行转换
            if(!StringUtils.isEmpty(result)){ // 非空判断
                JSONObject jsonObject = JSON.parseObject(result); // 转换回json对象
                // 判断是否通过登录
                if(jsonObject.getInteger("code") == 200){
                    // {"code":200,"data":{"username":"admin"},"message":"登录成功"} 返回数据jsonObject示例
                    JSONObject data = jsonObject.getJSONObject("data");
                    //获取数据体中的用户名 并作为 加密一部分
                    String username = data.getString("username");
                    // jwt 加密 并设置到header中
                    // 加密内容 + 时长 ; 返回token
                    String token = jwtUtils.sign(username,duration);
                    // 设置 返回信息到responseHeaders里面
                    RequestContext.getCurrentContext().getResponse().setHeader("token",token);
                    RequestContext.getCurrentContext().getResponse().setHeader("username",username);
                }
                // 因为之前调用了getResponseDataStream，流读取了一次之后没有数据了，把返回json重新塞回去
                requestContext.setResponseBody(jsonObject.toJSONString());
            }else{
                // todo 异常情况
            }
        } catch (IOException e) {
            // 再次抛出运行时异常
            rethrowRuntimeException(e);
        }
        return null;
    }
}
